<template>
    <div v-move class="box">
        <div class="header"></div>
        <div>内容</div>
    </div>
</template>

<script setup lang="ts">
import { Directive, DirectiveBinding} from 'vue'
// 指令demo: 拖拽移动
// 无返回值，就不用传参了
let vMove:Directive<any, void> = (el: HTMLElement, binding: DirectiveBinding) => {
    let moveElement:HTMLDivElement = el.firstElementChild as HTMLDivElement
    console.log(moveElement);
    const mouseDown = (e: MouseEvent) => {
        let X = e.clientX - el.offsetLeft      // 计算偏差量
        let Y = e.clientY - el.offsetTop
        const move = (e: MouseEvent) => {
            console.log(e);
            el.style.left = e.clientX - X + 'px'
            el.style.top = e.clientY -Y + 'px'
        }
        document.addEventListener('mousemove', move)
        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', move)
        })
    }
    moveElement.addEventListener('mousedown', mouseDown)
} 
</script>

<style scoped lang="less">
.box {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 100px;
    height: 100px;
    border: 1px solid black;
    .header {
        height: 20px;
        background-color: black;
        &:hover {
            cursor: move;
        }
    }
}
</style>